import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mvvm_provider/base/multi_state_widget.dart';
import 'package:mvvm_provider/net/ltt_https.dart';
import 'package:mvvm_provider/page/home/states/home_detail_state.dart';
import 'package:mvvm_provider/page/home/widgets/recommend_widget.dart';
import 'package:status_bar_control/status_bar_control.dart';
import '../../../base/base_stateful_page.dart';
import '../../../base/provider_selector_widget.dart';
import '../../../routers/navigator_utils.dart';
import '../../../widgets/delay_button.dart';
import '../model/cartoon_model_entity.dart';
import '../view_model/home_detail_view_model.dart';
import '../widgets/bottom_content_widget.dart';
import '../widgets/des_widget.dart';
import '../widgets/novel_header_widget.dart';
import '../widgets/series_widget.dart';

/// FileName: HomeDetailPage
/// Description: 单页面,多接口 并发 请求数据案例
/// Author: muziyuting
/// Date: 2023/10/02
///

const APPBAR_SCROLL_OFFSET = 100;

class HomeDetailPage extends BasePage {
  final String imageUrl;
  const HomeDetailPage({super.key, required this.imageUrl});

  @override
  BasePageState<BasePage> getState() {
    return _HomeDetailPageState();
  }
}

class _HomeDetailPageState extends BasePageState<HomeDetailPage> {
  HomeDetailViewModel homeDetailViewModel = HomeDetailViewModel();
  @override
  void initState() {
    super.initState();
    isRenderHeader = false;
    pageBgColor = const Color(0xFFF3F4F8);
    _getData();
  }

  @override
  void dispose() {
    /// 记得释放 viewModel
    super.dispose();
    homeDetailViewModel.dispose();
    LttHttp().cancelRequest();
  }

  /// 请求数据
  _getData() {
    homeDetailViewModel.getAllData();
  }

  _onScroll(offset) {
    /// offset滚动距离
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }

    if (alpha == 0) {
      StatusBarControl.setStyle(StatusBarStyle.LIGHT_CONTENT);
    } else if (alpha == 1) {
      StatusBarControl.setStyle(StatusBarStyle.DARK_CONTENT);
    }

    homeDetailViewModel.changeAppBarAlphaAndOffset(alpha, offset);
  }

  /// 导航栏
  Widget navWidget(CartoonModelData cartoonModelData, double appBarAlpha, double offset) {
    /// 改变元素透明度,自定义了一个appbar
    return Opacity(
      opacity: appBarAlpha,
      child: Container(
        height: statusBarH + kToolbarHeight,
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 50.w, right: 50.w, top: 40.h),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(width: 1.h, color: Colors.black12),
          ),
        ),
        child: Row(
          children: [
            Container(
              width: offset >= 150.h ? 1.sw - 150.w : 1.sw - 110.w,
              margin: EdgeInsets.only(right: 10.w),
              child: Text(
                cartoonModelData.title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 15.sp),
              ),
            ),
            Visibility(
              visible: offset >= 150.h ? true : false,
              child: Container(
                alignment: Alignment.center,
                width: 40.w,
                height: 20.h,
                decoration: BoxDecoration(
                    color: Colors.orange,
                    border: Border.all(width: 1.w, color: Colors.orange),
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(6.h), bottomRight: Radius.circular(6.h))),
                child: Text(
                  '追书',
                  style:
                      TextStyle(color: Colors.white, fontSize: 12.sp, fontWeight: FontWeight.w500),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 返回按钮
  Widget backBtn(double appBarAlpha) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        DelayButton(
          width: 48.w,
          margin: EdgeInsets.only(top: 20.h),
          height: ScreenUtil().statusBarHeight + kToolbarHeight,
          onTap: () {
            NavigatorUtils.pop(context);
          },
          mainWidget: Align(
            child: Image.asset("assets/images/back_black.png",
                fit: BoxFit.cover,
                color: appBarAlpha == 1 ? Colors.black : Colors.white,
                width: 26.w,
                height: 30.w),
          ),
        ),
        DelayButton(
          width: 48.w,
          margin: EdgeInsets.only(top: 20.h),
          height: ScreenUtil().statusBarHeight + kToolbarHeight,
          onTap: () {
            StatusBarControl.setStyle(StatusBarStyle.DARK_CONTENT);
          },
          mainWidget: Align(
            child: Image.asset("assets/images/ZCIcon_share_normal@3x.png",
                fit: BoxFit.cover,
                color: appBarAlpha == 1 ? Colors.black : Colors.white,
                width: 26.w,
                height: 26.w),
          ),
        ),
      ],
    );
  }

  /// 底部widget
  Widget bottomWidget(CartoonModelData mainModel) {
    return Positioned(
        left: 0,
        bottom: bottomSafeBarH,
        child: BottomContentWidget(
          epList: mainModel.ep,
        ));
  }

  @override
  Widget buildPage(BuildContext context) {
    return Stack(
      children: [
        //移除上部的距离
        MediaQuery.removePadding(
          removeTop: true, //移除上部
          context: context,
          //监听滚动
          child: NotificationListener(
            onNotification: (scrollNotification) {
              if (scrollNotification is ScrollUpdateNotification && scrollNotification.depth == 0) {
                //发生滚动并且是第0个元素
                _onScroll(scrollNotification.metrics.pixels);
              }
              return false;
            },
            child: Container(
              color: Colors.white,
              margin: EdgeInsets.only(bottom: bottomSafeBarH + 40.h),

              /// 头部widget && 描述widget
              child: ProviderSelectorWidget<HomeDetailViewModel, int>(
                  viewModel: homeDetailViewModel,
                  isValue: true,
                  builder: (context, id, child) {
                    HomeDetailState state = homeDetailViewModel.homeDetailState;
                    return MultiStateWidget(
                        placeHolderType: PlaceHolderType.detailPlaceHolder,
                        netState: state.netState,
                        builder: (BuildContext context) {
                          return ListView(
                            physics: const ClampingScrollPhysics(),
                            children: [
                              NovelHeaderWidget(
                                model: state.mainModel!,
                                imageUrl: widget.imageUrl,
                              ),
                              DesWidget(
                                model: state.mainModel!,
                              ),
                              SeriesWidget(seriesList: state.seriesList),
                              RecommendWidget(list: state.recommendList)
                            ],
                          );
                        });
                  },
                  selector: (context, id) =>
                      homeDetailViewModel.homeDetailState.mainModel?.id ?? 0),
            ),
          ),
        ),

        /// 子节点刷新,不刷新根节点
        ProviderSelectorWidget<HomeDetailViewModel, double>(
            viewModel: homeDetailViewModel,
            isValue: true,
            builder: (context, offset, child) {
              HomeDetailState state = homeDetailViewModel.homeDetailState;
              return state.mainModel == null
                  ? const SizedBox()
                  : navWidget(state.mainModel!, state.appBarAlpha, offset);
            },
            selector: (context, bookShelfViewModel) => homeDetailViewModel.homeDetailState.offset),

        /// 子节点刷新,不刷新根节点
        ProviderSelectorWidget<HomeDetailViewModel, double>(
            viewModel: homeDetailViewModel,
            isValue: true,
            builder: (context, appBarAlpha, child) {
              return backBtn(appBarAlpha);
            },
            selector: (context, bookShelfViewModel) =>
                homeDetailViewModel.homeDetailState.appBarAlpha),

        ProviderSelectorWidget<HomeDetailViewModel, int>(
            viewModel: homeDetailViewModel,
            isValue: true,
            builder: (context, id, child) {
              return homeDetailViewModel.homeDetailState.mainModel == null
                  ? const SizedBox()
                  : bottomWidget(homeDetailViewModel.homeDetailState.mainModel!);
            },
            selector: (context, bookShelfViewModel) =>
                bookShelfViewModel.homeDetailState.mainModel?.id ?? 0),

        Positioned(
            child: Center(
          child: Container(
            alignment: Alignment.center,
            width: 1.sw - 100.w,
            height: 50.h,
            color: Colors.blue,
            padding: EdgeInsets.symmetric(horizontal: 15.w),
            child: const Text(
              '单页面,多接口 并发 请求数据 + 局部刷新案例',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ))
      ],
    );
  }
}
